package com.example.framework.mqtt.core.config;

import com.example.framework.mqtt.core.annotation.MqttMessageListener;
import com.example.framework.mqtt.core.client.MqttPlatformClient;
import net.dreamlu.iot.mqtt.core.client.IMqttClientMessageListener;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *
 * </p>
 *
 * @author sfjiang
 * @since 2024/11/26 19:31
 */
public class MessageListenerProcessor implements SmartInitializingSingleton {

    private final MqttPlatformClient client;

    private final ApplicationContext applicationContext;

    public MessageListenerProcessor(MqttPlatformClient client, ApplicationContext applicationContext) {
        this.client = client;
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterSingletonsInstantiated() {
        // 获取所有标注了 @MqttMessageListener 的类
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(MqttMessageListener.class);
        if (!beans.isEmpty()) {
            Set<String> topicSet = new HashSet<>();
            for (Map.Entry<String, Object> entry : beans.entrySet()) {
                Object bean = entry.getValue();
                if (bean instanceof IMqttClientMessageListener) {
                    MqttMessageListener annotation = bean.getClass().getAnnotation(MqttMessageListener.class);
                    String[] topics = annotation.topics();
                    for (String topic : topics) {
                        if (StringUtils.isBlank(topic)) {
                            throw new IllegalArgumentException("[MessageListenerProcessor] failed! The topic cannot be null or empty.");
                        }
                        if (!topicSet.add(topic)) {
                            throw new IllegalStateException("[MessageListenerProcessor] failed! Because the application contains duplicate topics: " + topic);
                        }
                        client.subscribe(topic, annotation.qos(), (IMqttClientMessageListener) bean);
                    }
                } else {
                    throw new IllegalStateException("[MessageListenerProcessor] failed! The class annotated with @MqttMessageListener must implement IMqttClientMessageListener:" + bean.getClass().getName());
                }
            }
        }
    }
}
